 
use std::any::Any;
use std::sync::Arc;

use super::types::{CommandsContext, Disposer, ICommandHandler};
use super::imp::CommandsImplement;


/// 这是最终提供给其他插件的上下文对象
pub struct CommandsContextImpl {
    /// 持有对核心实现的引用
    commands_impl: Arc<CommandsImplement>,
    /// 贡献者（调用方插件）的名称
    contributor: String,
}

impl CommandsContextImpl {
    pub fn new(commands_impl: Arc<CommandsImplement>, contributor: &str) -> Self {
        Self {
            commands_impl,
            contributor: contributor.to_string(),
        }
    }
}

impl<'a> CommandsContext<'a> for CommandsContextImpl {
    fn register(&self, command_name: &str, handler: Box<dyn ICommandHandler>) -> Disposer<'a> {
        // TODO: 检查此 contributor 是否在 manifest 中声明了要贡献此 command_name
        
        self.commands_impl.register(command_name, handler);
        println!("Plugin '{}' registered command '{}'", self.contributor, command_name);

        // 返回一个清理函数
        let command_name_clone = command_name.to_string();
        let contributor_clone = self.contributor.clone();
        Box::new(move || {
            // TODO: 实现真正的移除逻辑
            println!("Disposing command '{}' from plugin '{}'", command_name_clone, contributor_clone);
        })
    }

    fn execute(&self, command_name: &str, args: Arc<dyn Any + Send + Sync>) -> Result<Arc<dyn Any + Send + Sync>, String> {
        // TODO: 检查此 contributor 是否有权限执行此 command
        self.commands_impl.execute(command_name, args)
    }
}